package com.durian.base.net.request;

import com.durian.base.net.HttpConfig;
import com.durian.base.net.HttpResponse;
import com.durian.base.net.ISyncHttpTask;
import com.durian.base.net.Utils;
import com.durian.base.net.cache.IHttpCacheManager;

import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Request;

/**
 * 说明：AbstractSyncHttpTask
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019/1/30 17:22
 * <p/>
 * 版本：version 1.0
 */
public abstract class AbstractSyncHttpTask implements ISyncHttpTask {

    protected String            url;
    protected IHttpCacheManager mHttpCacheManager;
    protected String            cacheKey = "";
    protected long              timeOut        = HttpConfig.Constant.TIME_OUT;
    protected Call              mCall;

    public AbstractSyncHttpTask(String url) {
        this.url = url;
    }

    public abstract Request.Builder createRequestBuilder();

    protected HttpResponse doInBackground() {
        Request.Builder builder = createRequestBuilder();
        if (builder != null) {
            Request request = builder.build();
            try {
                if (timeOut == HttpConfig.Constant.TIME_OUT) {
                    mCall = HttpConfig.get().client().newCall(request);
                } else {
                    mCall = HttpConfig.get().client().newBuilder().readTimeout(timeOut, TimeUnit.SECONDS).writeTimeout(timeOut, TimeUnit.SECONDS).connectTimeout(timeOut, TimeUnit.SECONDS).build().newCall(request);
                }
                return HttpResponse.response(mCall.execute());
            } catch (Exception e) {
                Utils.eLog(e);
                if (e instanceof SocketTimeoutException || (e != null && e instanceof InterruptedException && (e.getMessage() != null && "timeout".equals(e.getMessage().toLowerCase())))) {
                    return HttpResponse.timeOut(e);
                } else {
                    return HttpResponse.unkown(e);
                }
            }
        } else {
            return HttpResponse.nullResponse();
        }
    }

    @Override
    public String getUrl() {
        return url;
    }

    @Override
    public void cancelTask() {
        doCancelTask();
    }

    /**
     * 取消任务执行
     */
    protected void doCancelTask(){ }
}
